package org.example.router.impl;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.example.client.ServiceBClient;
import org.example.common.Constants;
import org.example.common.R;
import org.example.po.Routerparameters;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
@Component("SpecialRouterImpl")
public class SpecialRouterImpl extends RouterAbstract{
    @Override
    public boolean execute(Map<String, String> map, HttpServletResponse response) throws Exception {
        String tradeCode = map.get("rulename");
        String projectName = map.get("projectName");
        List<Routerparameters> list = searchDatabase(tradeCode + "_" + projectName);
        if(list == null){
            return true;
        }
        for (Routerparameters routerparameter : list) {
            String field = routerparameter.getRuleid();
            String value = routerparameter.getRulevalue();
            String o = map.get(field);
            if (StringUtils.isNotBlank(o) && decisionLogic(o,routerparameter)) {
                LOGGER.info("准备转发");

                R result = R.error();
                result.setMessage("未配置对应的处理逻辑");

                String methodName = map.get("method");

                //通过反射工具类，根据方法名来获得方法对象
                Method method = ReflectUtil.getMethodByName(ServiceBClient.class, methodName);
                //反射调用
                result = (R) method.invoke(serviceBClient, map);

                String s = JSON.toJSONString(result);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(s);
                return false;
            }
        }
        return true;
    }


    private boolean decisionLogic (String value, Routerparameters routerparameters){
        switch (Integer.parseInt(routerparameters.getRuleLimitType())) {
                //等于
            case Constants.RuleLimitType.EQUAL:
                return value.equals(routerparameters.getRulevalue());
                //大于
            case Constants.RuleLimitType.GT:
                return Double.parseDouble(value) > Double.parseDouble(routerparameters.getRulevalue());
                //小于
            case Constants.RuleLimitType.LT:
                return Double.parseDouble(value) < Double.parseDouble(routerparameters.getRulevalue());
                //大于等于
            case Constants.RuleLimitType.GE:
                return Double.parseDouble(value) >= Double.parseDouble(routerparameters.getRulevalue());
                //小于等于
            case Constants.RuleLimitType.LE:
                return Double.parseDouble(value) <= Double.parseDouble(routerparameters.getRulevalue());
            default:
                return false;
        }
    }
}
